package com.crazy.crazytransactionservice.message;

import com.crazy.crazytransactionservice.service.BuyService;
import com.crazy.crazytransactionservice.service.RedeemService;
import com.rabbitmq.client.Channel;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.support.AmqpHeaders;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.messaging.handler.annotation.Header;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;
import java.util.Map;
import java.util.Set;

/**
 * @Date: 2024-05-13-14:14
 * @Author: Zheng Zeliang
 */
@Component
@Slf4j
public class MessageConsumer {
    @Resource
    private RedisTemplate redisTemplate;
    @Resource
    private BuyService buyService;
    @Resource
    private RedeemService redeemService;

    @SneakyThrows
    @RabbitListener(queues = {"subscribe_queue"}, ackMode = "MANUAL")
    public void receiveSubscribeConfirm(Map<String, Integer> message, Channel channel, @Header(AmqpHeaders.DELIVERY_TAG) long deliverTag) {
        log.info("MQ接收到消息 = {}", message);
        Set<String> keySet = message.keySet();
        Integer transactionId = null;
        String messageId = null;
        for (String key : keySet) {
            messageId = key;
            transactionId = message.get(messageId);
        }
        try {
            buyService.confirmSubscribe(transactionId);
            channel.basicAck(deliverTag, false);
            redisTemplate.opsForValue().set(messageId,"consumed");
        } catch (Exception e) {
            e.printStackTrace();
            log.info("MQ拒绝消息");
            channel.basicNack(deliverTag, false, false);
        }
    }

    @SneakyThrows
    @RabbitListener(queues = {"redeem_queue"}, ackMode = "MANUAL")
    public void receiveRedeemConfirm(Map<String, Integer> message, Channel channel, @Header(AmqpHeaders.DELIVERY_TAG) long deliverTag) {
        log.info("MQ接收到消息 = {}", message);
        Set<String> keySet = message.keySet();
        Integer transactionId = null;
        String messageId = null;
        for (String key : keySet) {
            messageId = key;
            transactionId = message.get(messageId);
        }
        try {
            redeemService.confirmRedeem(transactionId);
            channel.basicAck(deliverTag, false);
            redisTemplate.opsForValue().set(messageId,"consumed");
        } catch (Exception e) {
            e.printStackTrace();
            log.info("MQ拒绝消息");
            channel.basicNack(deliverTag, false, false);
        }
    }
}

